package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.MenuDao;
import com.itheima.dto.PageResult;
import com.itheima.dto.QueryPageBean;
import com.itheima.pojo.Menu;
import com.itheima.service.MenuService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
@Transactional
public class MenuServiceImpl implements MenuService {
    @Autowired
    private MenuDao menuDao;

    /**
     * 分页查询所有的菜单
     *
     * @param queryPageBean
     * @return
     */
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        String queryString = queryPageBean.getQueryString();
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        PageHelper.startPage(currentPage, pageSize);
        Page<Menu> pages = menuDao.findAllMenu(queryString);
        return new PageResult(pages.getTotal(), pages.getResult());
    }

    /**
     * 用于角色的新增或者编辑,查询出所有的菜单,展示再表单中
     *
     * @return
     */
    public List<Menu> findAll() {
        return menuDao.findAll();
    }

    /**
     * 添加一个菜单
     *
     * @param
     * @return
     */
    public void add(Menu menu) {

        setPriority(menu);
        menuDao.add(menu);
    }

    private void setPriority(Menu menu){
        //设置优先级
        Integer priority = menu.getPriority();
        if(priority==null|| priority.equals(999999) ){
            //获取当前级别顶级菜单优先级
            Menu topMenu = this.menuDao.findTopOneMenu(menu.getLevel(),menu.getParentMenuId());
            if(topMenu!=null){
                menu.setPriority(topMenu.getPriority()+1);
                this.menuDao.updatePriority(topMenu.getLevel(),topMenu.getPriority()-1);
            }else {
                menu.setPriority(1);
            }
        }else {
            //查询上一优先级菜单
            Menu upMenu = this.menuDao.findById(priority);
            menu.setPriority(upMenu.getPriority()+1);
            this.menuDao.updatePriority(menu.getLevel(),upMenu.getPriority());//
        }
        //设置path
        //1、查询当前级别最后一个path
        Integer parentMenuId = menu.getParentMenuId();
        // select max(path) from t_menu where level = ? and <if test="pid = null"> parentMenuId is null</if> <if test="pid != null"> parentMenuId = #{pid}</if>
        String lastPath = this.menuDao.findLastPath(menu.getLevel(), parentMenuId);
        if(lastPath==null){//该级别下的第一个菜单
            if(parentMenuId==null){
                lastPath="/1";
            }else {
                List<Menu> list = new ArrayList<>();
                this.findParentMenu(list,parentMenuId);

                lastPath=parentMenuId+"-1";
                if(list!=null){
                    for (Menu menu1 : list) {
                        lastPath=menu1.getId()+"-"+lastPath;
                    }
                }
                lastPath="/"+lastPath;
            }

        }else {
            lastPath = lastPath.replace("/", "");
            String[] split = lastPath.split("-");//12-2-3
            if(split.length>0){
                split[split.length-1] = Integer.valueOf(split[split.length-1])+1+"";
            }
            lastPath = "/"+ StringUtils.join(split, "-");
        }
        System.out.println(lastPath);
        menu.setPath(lastPath);
    }


    private void findParentMenu(List<Menu> list,Integer id){
        Menu pMenu = this.findParentMenuById(id);
        if(pMenu!=null){
            list.add(pMenu);
            this.findParentMenu(list,pMenu.getId());
        }
    }

    private Menu findParentMenuById(Integer id){
        return this.menuDao.findParentMenuById(id);
    }

    /**
     * 用于编辑一个菜单的数据的回显
     *
     * @param
     * @return
     */
    public Menu findById(Integer id) {
        Menu menu = menuDao.findById(id);
        Menu menu1 = this.menuDao.findBeforeMenu(menu.getPriority(),menu.getLevel(),menu.getParentMenuId());

        if(menu1!=null){
            menu.setPriority(menu1.getId());
        }else {
            menu.setPriority(null);
        }
        return menu;
    }

    /**
     * 用于编辑一个菜单
     *
     * @param menu
     */
    public void edit(Menu menu) {
        setPriority(menu);
        menuDao.edit(menu);
    }

    /**
     * 用于删除一个菜单
     *
     * @param id
     */
    public void delete(Integer id) {
        //菜单等级查询
        Integer level = menuDao.findLevel(id);
        //一级菜单
        if (level == 1) {
            List<Integer> ids = menuDao.findLevel1Children(id);
            if (ids != null && ids.size() > 0) {
                for (Integer integer : ids) {
                    delete2(integer);
                }
            }
            delete3(id);
            return;
        }
        //二级菜单
        if (level == 2) {
            delete2(id);
            return;
        }
        //三菜单s
        if (level == 3) {
            delete3(id);
            return;
        }
    }



    public void delete2(Integer id) {
        //查找二级菜单下的三级菜单id
        List<Integer> ids = menuDao.findLevel2Children(id);
        if (ids != null && ids.size() > 0) {
            for (Integer i : ids) {
                delete3(i);
            }
        }
        delete3(id);
    }

    public void delete3(Integer id) {
        menuDao.deleteAndRoleAssiation(id);
        menuDao.delete(id);
    }

    /**
     * 用于查询所有的自关联Id
     *
     * @param
     */
    public List<Map> findMenuparentMenuId() {

        List list = new ArrayList<>();
   /*     Map map = new HashMap<>();
        map.put("value", "999999");
        map.put("label", "一级菜单");
        list.add(map)*/;

        ArrayList<Menu> menus = (ArrayList<Menu>) menuDao.findMenuparentMenuId();


        for (Menu menu : menus) {

            Integer id = menu.getId();
            Map mapc = new HashMap<>();


            mapc.put("value", id);
            mapc.put("label", menu.getName());

            if (menu.getParentMenuId() == null) {
                List<Menu> children = menu.getChildren();
                if (children.size() > 0) {
                    findChildren(mapc, children, id);
                }
            }

            list.add(mapc);
        }


        return list;
    }


    public List findChildren(Map map, List<Menu> children, Integer id) {
        List clits = new ArrayList<>();

        for (Menu child : children) {
            Map mapc = new HashMap();

            mapc.put("value", child.getId());
            mapc.put("label", child.getName());
            if (child.getChildren().size() != 0) {
                List m = findChildren(mapc, child.getChildren(), id);
                mapc.put("children", m);
            }

            clits.add(mapc);
            id++;
        }
        map.put("children", clits);
        return clits;
    }


    /**
     * 用于编辑的时候查询除了自己的id的所有的id
     *
     * @param
     * @return
     */
    public List<Map> findMenuIdAndDisabled(Integer cid) {
        List list = new ArrayList<>();
        Map map = new HashMap<>();
/*        map.put("value", null);
        map.put("label", "一级菜单");
        list.add(map);*/

        ArrayList<Menu> menus = (ArrayList<Menu>) menuDao.findMenuparentMenuId();
        for (int i = 0; i < menus.size(); i++) {
            Integer id = menus.get(i).getId();
            if (id == cid) {
                menus.remove(i);
                break;
            } else {
                Menu menu = menus.get(i);
                if (menu.getChildren() != null && menu.getChildren().size() > 0) {
                    removeParentMenuId(cid, menu.getChildren());
                }
            }
          /*  if (id == cid) {
                menus.remove(i);
                break;
            } else {

                List<Menu> children = menus.get(i).getChildren();
                for (int j = 0; j < children.size(); j++) {
                    Integer id1 = children.get(j).getId();
                    if (id1 == cid) {
                        children.remove(j);
                        break;
                    }

                }

            }*/


        }

        for (Menu menu : menus) {
            Integer id = menu.getId();
            Map mapc = new HashMap<>();
            mapc.put("value", id);
            mapc.put("label", menu.getName());
            if (menu.getParentMenuId() == null) {
                List<Menu> children = menu.getChildren();
                if (children.size() > 0) {
                    findChildren(mapc, children, id);
                }
            }
            list.add(mapc);
        }


        return list;
    }

    @Override
    public List<Integer> findParentIdsByMenuId(Integer mid) {
        List<Menu> list = new ArrayList<>();
        this.findParentMenu(list,mid);
        List<Integer> ids = new ArrayList<>();
        for (Menu menu : list) {
            ids.add(menu.getId());
        }
        return ids;
    }

    /**
     * 递归查找子集菜单删除对应id
     */
    private void removeParentMenuId(Integer cid, List<Menu> menus) {
        for (int j = 0; j < menus.size(); j++) {
            Integer id1 = menus.get(j).getId();
            if (id1 == cid) {
                menus.remove(j);
                break;
            } else {
                removeParentMenuId(cid, menus.get(j).getChildren());
            }

        }


    }


}

